<template>
  <view class="register-container">
    <view class="register-header">
      <text class="register-title">注册</text>
      <text class="register-subtitle">加入福州旅游大家庭</text>
    </view>

    <view class="register-form">
      <!-- Username Input -->
      <view class="form-group">
        <view class="input-wrapper" :class="{ 'error': errors.username }">
          <input
            class="form-input"
            type="text"
            placeholder="请输入用户名"
            v-model="formData.username"
            @input="onUsernameInput"
            @blur="validateUsername"
            :disabled="loading"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
      </view>

      <!-- Password Input -->
      <view class="form-group">
        <view class="input-wrapper" :class="{ 'error': errors.password }">
          <input
            class="form-input"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="formData.password"
            @input="onPasswordInput"
            @blur="validatePassword"
            :disabled="loading"
          />
          <view class="password-toggle" @tap="togglePassword">
            <text class="toggle-icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
      </view>

      <!-- Phone Input -->
      <view class="form-group">
        <view class="input-wrapper" :class="{ 'error': errors.phone }">
          <input
            class="form-input"
            type="number"
            placeholder="请输入手机号"
            v-model="formData.phone"
            @input="onPhoneInput"
            @blur="validatePhone"
            :disabled="loading"
            maxlength="11"
          />
        </view>
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
      </view>

      <!-- Register Button -->
      <button
        class="register-btn"
        :class="{ 'disabled': !canSubmit || loading }"
        :disabled="!canSubmit || loading"
        @tap="handleRegister"
      >
        <text v-if="loading" class="loading-text">注册中...</text>
        <text v-else>注册</text>
      </button>

      <!-- Login Link -->
      <view class="login-link">
        <text class="link-text">已有账号？</text>
        <text class="link-action" @tap="goToLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { AuthService } from '../../utils/auth.js';
import { ValidationUtils } from '../../utils/validation.js';

export default {
  data() {
    return {
      formData: {
        username: '',
        password: '',
        phone: ''
      },
      errors: {},
      loading: false,
      showPassword: false
    };
  },
  computed: {
    canSubmit() {
      return this.formData.username.trim() !== '' && 
             this.formData.password.trim() !== '' && 
             this.formData.phone.trim() !== '' &&
             !ValidationUtils.hasErrors(this.errors);
    }
  },
  methods: {
    /**
     * Handle username input change
     */
    onUsernameInput(e) {
      this.formData.username = e.detail.value;
      // Clear username error when user starts typing
      if (this.errors.username) {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'username');
      }
    },

    /**
     * Handle password input change
     */
    onPasswordInput(e) {
      this.formData.password = e.detail.value;
      // Clear password error when user starts typing
      if (this.errors.password) {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'password');
      }
    },

    /**
     * Handle phone input change
     */
    onPhoneInput(e) {
      this.formData.phone = e.detail.value;
      // Clear phone error when user starts typing
      if (this.errors.phone) {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'phone');
      }
    },

    /**
     * Validate username field
     */
    validateUsername() {
      const validation = ValidationUtils.validateUsername(this.formData.username);
      if (!validation.isValid) {
        this.$set(this.errors, 'username', validation.error);
      } else {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'username');
      }
    },

    /**
     * Validate password field
     */
    validatePassword() {
      const validation = ValidationUtils.validatePassword(this.formData.password);
      if (!validation.isValid) {
        this.$set(this.errors, 'password', validation.error);
      } else {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'password');
      }
    },

    /**
     * Validate phone field
     */
    validatePhone() {
      const validation = ValidationUtils.validatePhone(this.formData.phone);
      if (!validation.isValid) {
        this.$set(this.errors, 'phone', validation.error);
      } else {
        this.errors = ValidationUtils.clearFieldError(this.errors, 'phone');
      }
    },

    /**
     * Toggle password visibility
     */
    togglePassword() {
      this.showPassword = !this.showPassword;
    },

    /**
     * Handle registration form submission
     */
    async handleRegister() {
      if (!this.canSubmit || this.loading) {
        return;
      }

      // Validate form before submission
      const validation = ValidationUtils.validateRegistrationForm(this.formData);
      if (!validation.isValid) {
        this.errors = validation.errors;
        return;
      }

      this.loading = true;

      try {
        await AuthService.register(
          this.formData.username,
          this.formData.password,
          this.formData.phone
        );

        // Show success message
        uni.showToast({
          title: '注册成功',
          icon: 'success',
          duration: 1500
        });

        // Navigate to login page after short delay
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/auth/login',
            animationType: 'slide-in-left',
            animationDuration: 300
          });
        }, 1500);

      } catch (error) {
        // Show error message with appropriate feedback
        let errorMessage = '注册失败，请重试';
        
        // Handle specific error types according to requirements
        if (error.message) {
          if (error.message.includes('网络连接失败') || error.message.includes('请求超时')) {
            // Network-related errors (Requirement 5.3)
            errorMessage = error.message;
          } else {
            // Server-provided error messages (Requirement 1.4)
            errorMessage = error.message;
          }
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        });
        
        // Log error for debugging
        console.error('Registration failed:', error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * Navigate to login page
     */
    goToLogin() {
      uni.navigateTo({
        url: '/pages/auth/login',
        animationType: 'slide-in-left',
        animationDuration: 300
      });
    }
  }
};
</script>

<style lang="scss">
@import "../../uni.scss";

.register-container {
  min-height: 100vh;
  background-color: $uni-bg-color;
  padding: 60rpx 40rpx 40rpx;
  box-sizing: border-box;
}

.register-header {
  text-align: center;
  margin-bottom: 80rpx;
}

.register-title {
  font-size: 48rpx;
  font-weight: bold;
  color: $uni-text-color;
  display: block;
  margin-bottom: 20rpx;
}

.register-subtitle {
  font-size: 28rpx;
  color: $uni-text-color-grey;
  display: block;
}

.register-form {
  width: 100%;
}

.form-group {
  margin-bottom: 40rpx;
}

.input-wrapper {
  position: relative;
  border: 2rpx solid $uni-border-color;
  border-radius: $uni-border-radius-lg;
  background-color: $uni-bg-color;
  transition: border-color 0.3s ease;

  &.error {
    border-color: $uni-color-error;
  }

  &:focus-within {
    border-color: #FF6B6B;
  }
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 30rpx;
  font-size: $uni-font-size-base;
  color: $uni-text-color;
  background-color: transparent;
  border: none;
  box-sizing: border-box;

  &::placeholder {
    color: $uni-text-color-placeholder;
  }

  &:disabled {
    opacity: $uni-opacity-disabled;
  }
}

.password-toggle {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
}

.toggle-icon {
  font-size: 32rpx;
  color: $uni-text-color-grey;
}

.error-text {
  font-size: $uni-font-size-sm;
  color: $uni-color-error;
  margin-top: 10rpx;
  margin-left: 30rpx;
  display: block;
}

.register-btn {
  width: 100%;
  height: 88rpx;
  background-color: #FF6B6B;
  color: $uni-text-color-inverse;
  border: none;
  border-radius: $uni-border-radius-lg;
  font-size: $uni-font-size-lg;
  font-weight: bold;
  margin: 60rpx 0 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease, opacity 0.3s ease;

  &.disabled {
    background-color: $uni-text-color-disable;
    opacity: $uni-opacity-disabled;
  }

  &:not(.disabled):active {
    background-color: #e55a5a;
  }
}

.loading-text {
  color: $uni-text-color-inverse;
}

.login-link {
  text-align: center;
  margin-top: 40rpx;
}

.link-text {
  font-size: $uni-font-size-base;
  color: $uni-text-color-grey;
}

.link-action {
  font-size: $uni-font-size-base;
  color: #FF6B6B;
  margin-left: 10rpx;
  text-decoration: underline;
  transition: color 0.3s ease;
  
  &:active {
    color: #e55a5a;
  }
}
</style>